<template>
  <div class="company-plan">
    <div class="content">
      <Form
        :model="formState"
        style="width: 1010px"
        :label-col="{ style: { width: '210px' } }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        label-align="right"
        :colon="false"
      >
        <div class="hint-text">
          <p
            >您当前使用的是系统提供的统一的方案，该方案提供了系统登陆页面、登录后系统色调、顶部logo等设置。
            您可以开启个性方案配置，配置您企业的专属方案，若您需要，请开启下面开关，并按提示信息进行配置。
            注：当您配置完成后，需要在访问地址链接后方，增加您的路径方案编码，即可访问您的专属方案。
          </p>
          <FormItem
            name="SETPLAN_PRIVATE_ENABLE"
            label="开启个性方案"
            style="width: 100px"
            label-align="left"
            class="hint-text-switch"
          >
            <Switch v-model:value="formState.SETPLAN_PRIVATE_ENABLE" />
          </FormItem>
        </div>
        <div v-if="formState.SETPLAN_PRIVATE_ENABLE == '1'" class="program">
          <FormItem
            v-if="formState && formState.SETPLAN_IS_DEFULT === '1'"
            name="JE_SYS_PATHSCHEME"
            class="JE_SYS_PATHSCHEME"
            :label="$t('basic.secondary.path')"
            v-bind="validateInfos.JE_SYS_PATHSCHEME"
          >
            <Input
              v-model:value="formState.JE_SYS_PATHSCHEME"
              class="nim-input"
              disabled="disabled"
              :maxlength="10"
            />
            <div class="text">
              <i>{{ $t('basic.secondary.pathTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            v-else
            name="JE_SYS_PATHSCHEME"
            class="JE_SYS_PATHSCHEME"
            :label="$t('basic.secondary.path')"
            v-bind="validateInfos.JE_SYS_PATHSCHEME"
          >
            <Input v-model:value="formState.JE_SYS_PATHSCHEME" class="nim-input" :maxlength="10" />
            <div class="text">
              <i>{{ $t('basic.secondary.pathTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="JE_SYS_PATHSCHEMENAME"
            class="path"
            v-bind="validateInfos.JE_SYS_PATHSCHEMENAME"
          >
            <Input v-model:value="formState.JE_SYS_PATHSCHEMENAME" class="middle-input-s"></Input>
            <div class="text">
              <i>&nbsp;</i>
            </div>
          </FormItem>
          <FormItem
            name="JE_SYS_LOGINMETHOD"
            class="JE_SYS_LOGINMETHOD"
            :label="$t('basic.secondary.scheme')"
          >
            <RadioGroup
              v-model:value="formState.JE_SYS_LOGINMETHOD"
              :options="loginList"
              class="my-checkbox"
            />
            <div class="login-scheme">
              <div class="left">
                <div
                  class="palette"
                  :class="{ 'border-active': formState.JE_SYS_LOGINMETHOD === '1' }"
                >
                  <div class="scheme"><div class="gap"></div> </div>
                </div>
                <span>{{ $t('basic.secondary.scheme1') }}</span>
              </div>
              <div class="right">
                <div
                  class="palette"
                  :class="{ 'border-active': formState.JE_SYS_LOGINMETHOD === '2' }"
                >
                  <div class="scheme-last"></div>
                  <div class="scheme"><div class="gap"></div> </div>
                </div>
                <span>{{ $t('basic.secondary.scheme2') }}</span>
              </div>
            </div>
          </FormItem>
          <FormItem
            name="JE_SYS_LOGINCOLOR"
            class="JE_SYS_LOGINCOLOR"
            :label="$t('basic.secondary.loginCloor')"
          >
            <Color
              v-model:value="formState.JE_SYS_LOGINCOLOR"
              class="myInput"
              @change="changeColor"
            >
            </Color>
            <div class="text">
              <i>{{ $t('basic.secondary.loginCloorTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            class="JE_SYS_TITLELOGO"
            :label="$t('basic.secondary.systeLogo')"
            name="JE_SYS_TITLELOGO"
            v-bind="validateInfos.JE_SYS_TITLELOGO"
          >
            <Upload
              v-model:value="formState.JE_SYS_TITLELOGO"
              accept="image/*"
              :allow-clear="true"
              class="myInput"
            >
            </Upload>
            <div class="text">
              <i>{{ $t('basic.secondary.systeLogoTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            class="JE_SYS_BACKGROUNDLOGO"
            :label="$t('basic.secondary.background')"
            name="JE_SYS_BACKGROUNDLOGO"
            v-bind="validateInfos.JE_SYS_BACKGROUNDLOGO"
          >
            <Upload
              v-model:value="formState.JE_SYS_BACKGROUNDLOGO"
              :allow-clear="true"
              class="myInput"
            >
            </Upload>
            <div class="text">
              <i>{{ $t('basic.secondary.backgroundTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            class="JE_SYS_LEFTIMG"
            :label="$t('basic.secondary.img')"
            name="JE_SYS_LEFTIMG"
            v-bind="validateInfos.JE_SYS_LEFTIMG"
          >
            <Upload
              v-model:value="formState.JE_SYS_LEFTIMG"
              :allow-clear="true"
              class="myInput"
              accept=".png"
            >
            </Upload>
            <div class="text">
              <i class="color-red">{{ $t('basic.secondary.imgTip1') }}<br /></i>
              <i>{{ $t('basic.secondary.imgTip2') }}</i>
            </div>
          </FormItem>
        </div>
        <hr />
        <div v-if="formState.SETPLAN_PRIVATE_ENABLE == '1'" class="info">
          <FormItem
            class="JE_SYS_SYSNAME"
            name="JE_SYS_SYSNAME"
            :label="$t('basic.secondary.sysname')"
            v-bind="validateInfos.JE_SYS_SYSNAME"
          >
            <Input v-model:value="formState.JE_SYS_SYSNAME" class="myInput" />
            <div class="text">
              <i>{{ $t('basic.secondary.sysnameTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            class="JE_SYS_SYSURL"
            name="JE_SYS_SYSURL"
            :label="$t('basic.secondary.url')"
            v-bind="validateInfos.JE_SYS_SYSURL"
          >
            <Input v-model:value="formState.JE_SYS_SYSURL" class="myInput" />
            <div class="text">
              <i>{{ $t('basic.secondary.urlTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            class="JE_SYS_ICON"
            :label="$t('basic.secondary.icon')"
            name="JE_SYS_ICON"
            v-bind="validateInfos.JE_SYS_ICON"
          >
            <Upload v-model:value="formState.JE_SYS_ICON" :allow-clear="true" class="myInput">
            </Upload>
            <div class="text">
              <i>{{ $t('basic.secondary.iconTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            class="JE_SYS_WEBTITLE"
            name="JE_SYS_WEBTITLE"
            :label="$t('basic.secondary.Title')"
            v-bind="validateInfos.JE_SYS_WEBTITLE"
          >
            <Input v-model:value="formState.JE_SYS_WEBTITLE" class="myInput" />
            <div class="text">
              <i>{{ $t('basic.secondary.TitleTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            class="JE_SYS_WEBLOGO"
            :label="$t('basic.secondary.topLogo')"
            name="JE_SYS_WEBLOGO"
            v-bind="validateInfos.JE_SYS_WEBLOGO"
          >
            <Upload v-model:value="formState.JE_SYS_WEBLOGO" :allow-clear="true" class="myInput">
            </Upload>
            <div class="text">
              <i>{{ $t('basic.secondary.topLogoTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="JE_SYS_TOPMENU"
            class="JE_SYS_TOPMENU"
            :label="$t('basic.secondary.topMenu')"
          >
            <Select
              v-model="formState.JE_SYS_TOPMENU"
              :allow-clear="false"
              :default-value="formState.JE_SYS_TOPMENU"
              :options="menuList"
              class="myInput"
              @change="($event) => SelectChange('JE_SYS_TOPMENU', $event)"
            >
            </Select>
            <div class="text">
              <i>{{ $t('basic.secondary.topMenuTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="JE_SYS_DEFAULT_HUE"
            class="JE_SYS_DEFAULT_HUE"
            :label="$t('basic.secondary.hue')"
          >
            <RadioGroup v-model:value="formState.JE_SYS_DEFAULT_HUE">
              <RadioButton
                v-for="item in themes"
                :key="item.code"
                class="color-btn"
                :style="{ background: item.color }"
                :value="item.code"
              >
                <i
                  class="fal fa-check write-i"
                  :class="{ 'opcity-i': formState.JE_SYS_DEFAULT_HUE !== item.code }"
                ></i>
              </RadioButton>
            </RadioGroup>
            <div class="text">
              <i>{{ $t('basic.secondary.hueTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="JE_SYS_DEFAULT_MENUCOLOR"
            class="JE_SYS_DEFAULT_MENUCOLOR"
            :label="$t('basic.secondary.menuColor')"
          >
            <RadioGroup v-model:value="formState.JE_SYS_DEFAULT_MENUCOLOR">
              <RadioButton
                v-for="item in themes"
                :key="item.code"
                class="color-btn"
                :style="{ background: item.color }"
                :value="item.code"
              >
                <i
                  class="fal fa-check write-i"
                  :class="{ 'opcity-i': formState.JE_SYS_DEFAULT_MENUCOLOR !== item.code }"
                ></i>
              </RadioButton>
            </RadioGroup>
            <div class="text">
              <i>{{ $t('basic.secondary.hueTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="JE_SYS_GRAY_MODEL"
            class="JE_SYS_GRAY_MODEL"
            :label="$t('basic.secondary.garyMode')"
          >
            <Select
              v-model="formState.JE_SYS_GRAY_MODEL"
              :allow-clear="false"
              :default-value="formState.JE_SYS_GRAY_MODEL"
              :options="grayModelList"
              class="myInput"
              @change="($event) => SelectChange('JE_SYS_GRAY_MODEL', $event)"
            >
            </Select>
            <div class="text">
              <i>{{ $t('basic.secondary.garyModelTip') }}</i>
            </div>
          </FormItem>
        </div>
      </Form>
    </div>
  </div>
</template>

<script>
  import { defineComponent, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
  import { Form, Input, Color, Radio, Modal, Select, Upload, Switch } from '@jecloud/ui';
  import { cloneDeep, isNotEmpty } from '@jecloud/utils';
  import VueEvent from '@/helper/model/event';
  import { onScroll, scrollToTop } from '@/utils/utils';
  import { editScheme } from '@/api';
  import { useI18n } from '@common/locales';
  const useForm = Form.useForm;

  export default defineComponent({
    name: 'CompanyPlan',
    components: {
      Form,
      FormItem: Form.Item,
      Input,
      Color,
      RadioGroup: Radio.Group,
      RadioButton: Radio.Button,
      Select,
      Upload,
      Switch,
    },
    props: {
      dataAll: {
        type: Object,
        default: () => {},
      },
    },
    emits: ['showMain'],
    setup(props, { emit }) {
      // 表单数据
      let formState = reactive({
        SETPLAN_PRIVATE_ENABLE: '0',
        JE_SYS_PATHSCHEME: 'je',
        JE_SYS_PATHSCHEMENAME: '',
        JE_SYS_LOGINMETHOD: '1',
        JE_SYS_LOGINCOLOR: '#3265f5',
        JE_SYS_TITLELOGO: '',
        JE_SYS_BACKGROUNDLOGO: '',
        JE_SYS_LEFTIMG: '',
        JE_SYS_SYSNAME: '',
        JE_SYS_SYSURL: '',
        JE_SYS_ICON: '',
        JE_SYS_WEBTITLE: '',
        JE_SYS_WEBLOGO: '',
        // todo
        JE_SYS_TOPMENU: 'center',
        JE_SYS_GRAY_MODEL: '0',
        JE_SYS_DEFAULT_HUE: 'primary',
        JE_SYS_DEFAULT_MENUCOLOR: 'black',
        tableCode: 'JE_CORE_SETPLAN',
        SETPLAN_IS_DEFULT: '0',
      });

      let meta = {};

      onMounted(() => {
        loadFormData();
        // 回滚到顶部
        scrollToTop();
      });

      // 数据回显处理
      const loadFormData = () => {
        const companyConfig = props.dataAll.filter((item) => {
          return item.code === 'company-config';
        });
        if (isNotEmpty(companyConfig)) {
          companyConfig[0]?.items.find((item) => {
            formState[item.code] = item['value'];
          });
        }
        meta = cloneDeep(formState);
      };

      // 点击返回的函数:跳转还是弹框
      const handelClick = () => {
        if (!isChange()) {
          dialogEvent();
        } else {
          VueEvent.emit('saveResult', true);
        }
      };

      const SelectChange = (code, e) => {
        formState[code] = e;
      };

      // 得到所有产品方案
      // 优化回显

      // 字段值是否改变，用于判断和保存
      const isChange = () => {
        return Object.keys(meta).every((item) => {
          return meta[item] === formState[item];
        });
      };

      // 登录方案选项
      const I18n = useI18n().messages.zh_CN;
      const loginList = [
        { value: '1', label: I18n.basic.secondary.scheme1 },
        { value: '2', label: I18n.basic.secondary.scheme2 },
      ];

      // form表单校验

      // 校验规则
      const rules = {
        JE_SYS_PATHSCHEME: [
          {
            required: true,
            message: '该选项为必填项',
          },
          {
            pattern: /^[a-z_]*$/,
            message: '请输入小写字母',
          },
        ],
        JE_SYS_PATHSCHEMENAME: [
          {
            required: true,
            message: '该选项为必填项',
          },
          {
            pattern: /^[\u4e00-\u9fa5]{0,}$/,
            message: '仅支持输入中文',
          },
        ],
        JE_SYS_TITLELOGO: [
          {
            required: true,
            message: '该选项为必填项',
          },
        ],
        JE_SYS_BACKGROUNDLOGO: [
          {
            required: true,
            message: '该选项为必填项',
          },
        ],
        JE_SYS_LEFTIMG: [
          {
            required: true,
            message: '该选项为必填项',
          },
        ],
        JE_SYS_SYSNAME: [
          {
            required: true,
            message: '该选项为必填项',
          },
        ],
        JE_SYS_SYSURL: [
          {
            required: true,
            message: '该选项为必填项',
          },
          {
            pattern:
              /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i,
            message: '请输入正确网络地址格式',
          },
        ],
        JE_SYS_ICON: [
          {
            required: true,
            message: '该选项为必填项',
          },
        ],
        JE_SYS_WEBTITLE: [
          {
            required: true,
            message: '该选项为必填项',
          },
        ],
        JE_SYS_WEBLOGO: [
          {
            required: true,
            message: '该选项为必填项',
          },
        ],
      };
      const rulesRef = reactive(cloneDeep(rules));
      watch(
        () => formState.SETPLAN_PRIVATE_ENABLE,
        (newVal) => {
          Object.keys(rules).forEach((item) => {
            rulesRef[item] = newVal == '1' ? rules[item] : [];
          });
        },
        {
          immediate: true,
        },
      );
      // 监听方案一还是二更改校验对象
      watch(
        () => formState.JE_SYS_LOGINMETHOD,
        (val) => {
          if (val === '1') {
            rulesRef.JE_SYS_LEFTIMG = [{ required: false }];
            rulesRef.JE_SYS_BACKGROUNDLOGO = [
              {
                required: true,
                message: '该选项为必填项',
              },
            ];
          } else {
            rulesRef.JE_SYS_LEFTIMG = [
              {
                required: true,
                message: '该选项为必填项',
              },
            ];
            rulesRef.JE_SYS_BACKGROUNDLOGO = [{ required: false }];
          }
          if (formState.SETPLAN_PRIVATE_ENABLE == '0') {
            rulesRef.JE_SYS_LEFTIMG = [];
            rulesRef.JE_SYS_BACKGROUNDLOGO = [];
          }
        },
        { immediate: true },
      );

      // 校验方法
      const { validate, validateInfos } = useForm(formState, rulesRef, {
        // onValidate: (...args) => console.log(...args),
      });

      const onSubmit = (type) => {
        validate()
          .then(() => {
            if (!isChange()) {
              // 保存数据接口
              editScheme({
                ...formState,
              }).then(() => {
                meta = cloneDeep(formState);
                Modal.notice('保存成功', 'success');
                if (type) {
                  VueEvent.emit('saveResult', true);
                }
                VueEvent.emit('changeAllData', { item: 'company-config', formState });
              });
            } else {
              // 如果显示了子页面就不提示
              Modal.notice('无数据操作!', 'info');
            }
          })
          .catch((err) => {
            console.log('error', err);
          });
      };

      // 滚动
      const onScrollDe = () => {
        setTimeout(() => {
          onScroll();
        }, 0);
      };

      // 是否可以离开本页面
      const isCanLeave = ref(false);
      // 弹框
      const dialogEvent = async () => {
        Modal.dialog({
          content: '数据有改动，未保存，确定离开吗？',
          buttons: [
            {
              text: '确认离开',
              type: 'primary',
              closable: false,
              handler: ({ button, $modal }) => {
                button.loading = true;
                VueEvent.emit('saveResult', true);
                $modal.close();
              },
            },
            {
              text: '保存离开',
              type: 'primary',
              closable: false,
              handler: ({ button, $modal }) => {
                button.disabled = true;
                button.disabled = false;
                $modal.close();
                isCanLeave.value = true;
                onSubmit(true);
              },
            },
            {
              text: '取消',
            },
          ],
        });
      };

      // 登录页高亮元素颜色改变
      const changeColor = () => {
        if (!formState.JE_SYS_LOGINCOLOR) {
          setTimeout(() => {
            formState.JE_SYS_LOGINCOLOR = 'primary';
          });
        }
      };
      const menuList = [
        { label: '居左', value: 'start' },
        { label: '居右', value: 'end' },
        { label: '居中', value: 'center' },
      ];

      const grayModelList = [
        { label: '关闭', value: '0' },
        { label: '开启', value: '1' },
      ];

      // 颜色配置
      const themes = [
        { code: 'primary', color: '#3265F5', theme: 'primary', colour: 'dark' },
        { code: 'orange', color: '#F3752D', theme: 'orange', colour: 'dark' },
        { code: 'red', color: '#E34F47', theme: 'red', colour: 'dark' },
        { code: 'green', color: '#02A863', theme: 'green', colour: 'dark' },
        {
          code: 'black',
          color: '#2F3134',
          theme: 'primary',
          colour: 'dark',
          primaryAttrs: ['bgColor'],
        },
        {
          code: 'gray',
          color: '#F1F3F7',
          theme: 'primary',
          colour: 'light',
          primaryAttrs: ['textColor'],
        },
        {
          code: 'white',
          color: '#FFFFFF',
          theme: 'primary',
          colour: 'light',
          primaryAttrs: ['textColor'],
        },
      ];

      VueEvent.on('toolbarSaveEventS', onSubmit);
      VueEvent.on('fadeScrollSed', onScrollDe);
      VueEvent.on('isSave', handelClick);
      VueEvent.on('fadeScroll', onScroll);
      onUnmounted(() => {
        VueEvent.off('fadeScrollSed', onScrollDe);
        VueEvent.off('isSave', handelClick);
        VueEvent.off('toolbarSaveEventS', onSubmit);
        VueEvent.on('fadeScroll', onScroll);
      });

      return {
        handelClick,
        formState,
        loginList,
        SelectChange,
        validateInfos,
        menuList,
        grayModelList,
        changeColor,
        themes,
      };
    },
  });
</script>
<style lang="less">
  .company-plan {
    .content {
      .hint-text {
        &-switch {
          .ant-form-item-label {
            label {
              color: #bc7c25 !important;
            }
          }
        }
      }
    }
  }
</style>
<style lang="less" scoped>
  .company-plan {
    padding-top: 30px;
    font-size: 14px;
    .color-red {
      color: #e7a674;
    }
    .border-active {
      border: 2px solid primary;
    }
    .color-btn {
      .fa-check {
        font-weight: 500;
        font-size: 18px;
      }
      position: relative;
      margin-right: 13px;
      border-radius: 5px;
      border: 1px solid #dadada;
      &::before {
        opacity: 0;
      }
      .gray-i {
        position: absolute;
        top: 6px;
        left: 8px;
        color: A9ABA9;
      }
      .write-i {
        position: absolute;
        top: 6px;
        left: 8px;
        color: #fff;
      }
      .opcity-i {
        display: none;
      }
    }
    .active {
      border: 2px solid primary;
    }
    .content {
      .hint-text {
        background: #faf9da;
        padding: 25px 30px;
        border: 1px solid #c3893a;
        margin: 0 20px 20px 20px;
        color: #bc7c25;
        &-switch {
          margin-bottom: 0;
        }
      }
      .program {
        position: relative;
        padding-bottom: 10px;
      }
      .info {
        padding: 20px 0 10px 0;
      }
      position: relative;
      .select-all {
        width: 80px;
        height: 32px;
        border: 1px solid #d9d9d9;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .login-scheme {
        width: 370px;
        height: 150px;
        margin-top: 19px;
        display: flex;
        justify-content: space-between;
        .left,
        .right {
          width: 165px;
          height: 150px;
          display: flex;
          flex-direction: column;
          justify-content: space-around;
          align-items: center;
        }
        .palette {
          width: 160px;
          height: 116px;
          background: #f0f2f5;
          border-radius: 2px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .scheme,
        .scheme-last {
          position: relative;
          width: 60px;
          height: 65px;
          background: #ffffff;
          border: 1px solid #ffffff;
          border-radius: 6px;
        }
        .scheme-last {
          margin-right: 6px;
        }
        .gap {
          position: absolute;
          bottom: 12px;
          left: 16px;
          width: 28px;
          height: 7px;
          background: #f0f2f5;
          border: 1px solid #f0f2f5;
          border-radius: 1px;
        }
      }
      .nim-input {
        width: 120px;
      }
      .middle-input-s {
        width: 565px;
      }
      .middle-input {
        width: 605px;
      }
      .path {
        position: absolute;
        top: 0px;
        left: 342px;
      }
      .party {
        position: relative;
      }
      .produce {
        position: absolute;
        top: 0px;
        left: 302px;
      }
    }
  }
</style>
